package cn.funnymap.lgis.mp.handler;

import net.postgis.jdbc.PGgeometry;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 几何类型字段处理器
 *
 * @author jiao xn
 */
@ConditionalOnClass(BaseTypeHandler.class)
@MappedTypes(String.class)
public class GeometryTypeHandler extends BaseTypeHandler<String> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String parameter, JdbcType jdbcType) throws SQLException {
        if ("".equals(parameter)){
            preparedStatement.setObject(i, null);
        }else {
            PGgeometry pGgeometry = new PGgeometry(parameter);
            preparedStatement.setObject(i, pGgeometry);
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String string = rs.getString(columnName);
        return getResult(string);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String string = rs.getString(columnIndex);
        return getResult(string);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String string = cs.getString(columnIndex);
        return getResult(string);
    }


    private String getResult(String string) throws SQLException {
        if (string == null){
            return "";
        }
        PGgeometry pGgeometry = new PGgeometry(string);
        return pGgeometry.toString();
    }
}
